const routes = [{
        redirect: {
            name: 'index'
        },
        component: 'Layout',
        children: [{
            component: 'index/Index',
            meta: {
                title: '后台首页'
            }
        }, {
            component: 'shop/goods/List',
            meta: {
                title: '商品列表'
            }
        }, {
            component: 'test/Test',
            meta: {
                title: '测试页面111'
            }
        }, {
            component: 'test/Test2',
            meta: {
                title: '测试页面222'
            }
        }, {
            component: 'test/Test3',
            meta: {
                title: '测试页面333'
            }
        }]
    },
    {
        component: 'login/Index',
        meta: {
            title: '登录页'
        }
    },
    {
        path: '*',
        redirect: {
            path: '/index'
        }
    }
];

// 生成路由详细信息
let getRoutes = () => {
    // 自动生成路由
    createRoutes(routes);
    return routes;
};

// 自动创建路由
function createRoutes(arr) {
    for (let i = 0; i < arr.length; i++) {
        // 没有component直接返回
        if (!arr[i].component) return;

        // 去除index
        let val = getVal(arr[i].component);

        // 自动生成path
        if (val == 'Layout') {
            arr[i].path = arr[i].path || `/`;
        } else {
            arr[i].path = arr[i].path || `/${val.toLowerCase()}`;
        }

        // console.log('arr[i].path', arr[i].path);

        // 自动生成name
        arr[i].name = arr[i].name || val.replace(/\//g, '_').toLowerCase();

        // console.log('arr[i].name', arr[i].name);

        // 自动生成component
        let compFun = import(`@/views/${arr[i].component}`);
        arr[i].component = () => compFun;

        // 查看children进行递归
        if (arr[i].children && arr[i].children.length > 0) {
            createRoutes(arr[i].children);
        }
    }
}

// 去除index
function getVal(str) {
    // str = /login/Index
    // 获取最后一个/的索引
    let index = str.lastIndexOf('/');

    // 获取最后一个/后面的值
    let val = str.substring(index + 1);

    if (val.toLowerCase() == 'index') {
        return str.substring(index, -1);
    }
    return str;
}

export default getRoutes();